package com.ibeeking.found.msg.rest.service.mpevent;

import com.ibeeking.found.common.entity.open.OpenAuthDTO;
import com.ibeeking.found.common.enums.mp.WxMpSourceTypeEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.*;
import com.ibeeking.found.msg.service.common.bo.KeyWordBO;
import com.ibeeking.found.msg.service.common.param.WxMpAutoMsgParam;
import com.ibeeking.found.msg.service.common.query.CallBackQuery;
import com.ibeeking.found.msg.service.common.query.KeyWordQuery;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.data.StringUtils;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.builder.outxml.TextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;


/**
 * 回复消息
 *
 * @Author ibeeking
 */
@Component
public class MsgHandler  implements WxMpMessageHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IMpAutoMessageService mpAutoMessageServiceImpl;
    @Resource
    private IOpenService wxOpenServiceImpl;

    @Resource
    private IEventMsgService eventMsgServiceImpl;

    @Resource
    private IWxMpMsgService wxMsgServiceImpl;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String teantId = UserUtils.getTenantId();
        if(StringUtils.isBlank(teantId)){
            throw new BusinessException("无法获取租户TenantId!");
        }
        String appId = wxMpService.getWxMpConfigStorage().getAppId();
        Long tenantId = UserUtils.getTenantID();
        OpenAuthDTO wxOpenAuthDTO = wxOpenServiceImpl.queryWxOpenAuthByTenantIdAndAppId(tenantId, appId);
        //组装回复消息
        if (wxMessage.getMsgType().equals(WxConsts.XmlMsgType.TEXT)) {
            KeyWordQuery query = new KeyWordQuery();
            query.setAppId(wxOpenAuthDTO.getAppId());
            query.setKeyWord(wxMessage.getContent());
            KeyWordBO keyWordBO = mpAutoMessageServiceImpl.queryKeyWord(query);
            if (null != keyWordBO) {
                CallBackQuery callBackQuery = new CallBackQuery();
                callBackQuery.setAppId(wxOpenAuthDTO.getAppId());
                if (StringUtils.isNotBlank(keyWordBO.getSourceType())) {
                    callBackQuery.setSourceType(WxMpSourceTypeEnum.valueOf(keyWordBO.getSourceType()));
                    callBackQuery.setUnionKey(keyWordBO.getUnionKey());
                } else {
                    callBackQuery.setUnionKey("您可尝试输入".concat(keyWordBO.getUnionKey()).concat("试试。"));
                }
                WxMpXmlOutMessage out = eventMsgServiceImpl.callBackMsg(wxMessage, callBackQuery);
                record(wxMessage, wxOpenAuthDTO.getAppId(), callBackQuery.getUnionKey(), out);
                return out;
            }
        }
        String content = "暂时找不到您输入的问题";
        return new TextBuilder().content(content).fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()).build();
    }

    private void record(WxMpXmlMessage wxMessage, String appId, String unionKey, WxMpXmlOutMessage out) {
        WxMpAutoMsgParam param = new WxMpAutoMsgParam();
        param.setAppId(appId);
        param.setOpenId(wxMessage.getFromUser());
        param.setRepType(wxMessage.getMsgType());
        param.setRepEvent(wxMessage.getEvent());
        param.setUnionKey(unionKey);
        param.setReturnType(out.getMsgType());
        param.setRepContent(wxMessage.getContent());
        wxMsgServiceImpl.add(param);
    }
}
